import org.springframework.beans.factory.InitializingBean

import com.aliasi.dict.ApproxDictionaryChunker
import com.aliasi.dict.TrieDictionary
import com.aliasi.dict.DictionaryEntry
import com.aliasi.spell.FixedWeightEditDistance;

import org.opendream.roti.lingpipe.CharTokenizerFactory

class NameEntityService {

    // ApproxDictionaryChunker
    def chunker
    
    // map from nameEntity.id to NameEntity
    def nameEntityMap

    /**
     * return list of nameEntity
     */
    def extract(text) {
        def chunking = chunker.chunk(text)
        def chunkSet = chunking.chunkSet()
        def set = new HashSet()
        
        chunkSet.each() {
            set.add(it.type().toLong())
        }
        
        set.collect() {
            nameEntityMap[it]
        }
    }
    
    /**
     * refresh nameEntity cache
     */
    def refresh() {
        nameEntityMap = [:]
        
        def trie = new TrieDictionary();
        def names = NameEntity.list()
        names.each() {
            trie.addEntry(new DictionaryEntry(it.name, it.id.toString(), 1.0))
            nameEntityMap.put(it.id, it)
        }
        
        def maxDistance = 1.0;
        chunker = new ApproxDictionaryChunker(trie, 
            new CharTokenizerFactory(), 
            new FixedWeightEditDistance(0,-1,-1,-1,Double.NaN),
            maxDistance);
    }
    
    def getNameEntity(id) {
        nameEntityMap[id]
    }

}